/*
 * Copyright (c) 2013 哈尔滨亿时代数码科技开发有限公司（www.hrbesd.com）. All rights reserved.
 * 
 * HRBESD PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.esd.crm.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.esd.crm.Constants;
import com.esd.crm.entity.Customer;
import com.esd.crm.service.CustomerService;
import com.esd.crm.service.ProductService;

/**
 * 
 * 主页处理
 * 
 * @author zhangjianzong
 * 
 */
@Controller
@RequestMapping("/security")
public class CustomerController {

	private static final Logger logger = LogManager.getLogger(CustomerController.class);
	@Autowired
	private CustomerService customerService;
	@Autowired
	private ProductService productService;

	@RequestMapping(value = "/updateCustomer", method = RequestMethod.GET)
	public ModelAndView updateGet(HttpServletRequest request, HttpSession session) {
		
		String id = request.getParameter("id");
		Customer c = customerService.selectByPrimaryKey(Integer.valueOf(id));
		ModelAndView mv =new ModelAndView("customer/customer_update");
		mv.addObject("id", c.getId());
		mv.addObject("type", c.getType());
		mv.addObject("name", c.getName());
		mv.addObject("card", c.getCard());
		mv.addObject("idCard", c.getIdcard());
		mv.addObject("telephone", c.getTelephone());
		mv.addObject("company", c.getCompany());
		mv.addObject("remark", c.getRemark());
		mv.addObject(c);
		return mv;
	}

	/**
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/updateCustomer", method = RequestMethod.POST)
	public ModelAndView updatePost(HttpSession session, HttpServletRequest request, RedirectAttributes redirectAttributes) {
		Integer userId = (Integer) session.getAttribute(Constants.USER_ID);
		
		String id = request.getParameter("id");
		String type = request.getParameter("type");
		String name = request.getParameter("name");
		String card = request.getParameter("card");
		String idcard = request.getParameter("idcard");
		String telephone = request.getParameter("telephone");
		String company = request.getParameter("company");
		String remark = request.getParameter("remark");

		
		Customer c=customerService.selectByPrimaryKey(Integer.valueOf(id));
		//Customer c = new Customer();
		c.setType(type);
		c.setName(name);
		c.setCard(card);
		c.setIdcard(idcard);
		c.setTelephone(telephone);
		c.setCompany(company);
		c.setRemark(remark);
		
		c.setUpdatetime(new Date());
		c.setUpdateuser(userId);
		
		customerService.updateByPrimaryKeySelective(c);
		

		//redirectAttributes.addFlashAttribute(Constants.MESSAGE, "更新成功！");
		return new ModelAndView("redirect:/security/successAndClose");
	}

	@RequestMapping(value = "/customer", method = RequestMethod.GET)
	public ModelAndView customerGet() {
		return new ModelAndView("customer/customer");
	}

	@RequestMapping(value = "/customer", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> customerPost(HttpSession session, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		String type = request.getParameter("type");
		String name = request.getParameter("name");
		String company = request.getParameter("company");
		String telephone = request.getParameter("telephone");
		String status = request.getParameter("status");
		
		// 组合查询参数
		int page = Integer.valueOf(request.getParameter("page"));
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("page", (page - 1) * 20);
		param.put("totle", 20);
		
		//加载查询参数
		if(StringUtils.isNoneBlank(name)) {
			param.put("name", name);
		}
		if(StringUtils.isNoneBlank(type)) {
			param.put("type", type);
		}
		if(StringUtils.isNoneBlank(company)) {
			param.put("company", company);
		}
		if(StringUtils.isNoneBlank(telephone)) {
			param.put("telephone", telephone);
		}
		if(StringUtils.isNoneBlank(status)) {
			if(status.equals("已付")) {
				param.put("paid", status);
			}else if(status.equals("欠款")) {
				param.put("payable", status);
			}
		}
		
		List<Customer> list = customerService.selectByParam(param);
		int totle = customerService.selectByParamCount(param);
		int u = totle % 20;
		int pageCount = 1;
		if (u > 0) {
			pageCount = totle / 20 + 1;
		} else {
			pageCount = totle / 20;
		}
		
		for (Iterator<Customer> iterator = list.iterator(); iterator.hasNext();) {
			Customer customer = (Customer) iterator.next();
			if(customer.getTotal().equals(customer.getPaid())) {
				customer.setPaymentstatus("已付");
			}else {
				customer.setPaymentstatus("欠款");
			}
			
		}
		
		
		
		map.put(Constants.LIST, list);
		map.put(Constants.TOTLE, totle);
		map.put(Constants.TOTLE_PAGE, pageCount);
		return map;
	}


	/**
	 * 跳转添加客户页
	 */
	@RequestMapping(value = "/addCustomer", method = RequestMethod.GET)
	public ModelAndView addMarriageGet(HttpSession session) {
		logger.info("跳转添加客户页");
		return new ModelAndView("customer/customer_add");
	}

	@RequestMapping(value = "/addCustomer", method = RequestMethod.POST)
	public ModelAndView addCustomerPost(HttpSession session, HttpServletRequest request, RedirectAttributes redirectAttributes) {
		logger.info("进入添加客户页");
		Integer userId = (Integer) session.getAttribute(Constants.USER_ID);
		logger.info("获取表单信息");
		String type = request.getParameter("type");
		String name = request.getParameter("name");
		String card = request.getParameter("card");
		String idcard = request.getParameter("idCard");
		String telephone = request.getParameter("telephone");
		String company = request.getParameter("company");
		String remark = request.getParameter("remark");
		Customer c = new Customer();
		c.setType(type);
		c.setName(name);
		c.setCard(card);
		c.setIdcard(idcard);
		c.setTelephone(telephone);
		c.setCompany(company);
		c.setRemark(remark);
		c.setCreateuser(userId);
		logger.info(c.toString());
		customerService.insert(c);
		return new ModelAndView("redirect:/security/successAndClose");
	}

	@RequestMapping(value = "/delCustomer", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> delMarriage(HttpSession session, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		Customer c = customerService.selectByPrimaryKey(Integer.valueOf(id));
		productService.deleteByCustomerId(c.getId());
		customerService.deleteByPrimaryKey(c.getId());
		map.put(Constants.MESSAGE, "删除成功！");
		return map;
	}
	//
	// @RequestMapping(value = "/upload", method = RequestMethod.GET)
	// public ModelAndView uploadGet(HttpServletRequest request,
	// RedirectAttributes redirectAttributes) {
	// // String dir = request.getParameter("dir");
	// String userId = request.getParameter("userId");
	// // return new ModelAndView("marriage/upload", "dir", dir);
	// return new ModelAndView("marriage/upload", "userId", userId);
	//
	// }
	//
	// @RequestMapping(value = "/upload", method = RequestMethod.POST)
	// @ResponseBody
	// public void upload(HttpSession session, HttpServletRequest request,
	// @RequestParam MultipartFile file) {
	// // String dir = (String) request.getParameter("dir");
	// String userId = (String) request.getParameter("userId");
	// Marriage marriage = marriageService.selectByPrimaryKey(Integer
	// .valueOf(userId));
	// // =====================================
	// String path = marriage.getPhotoPath();
	// if (path.indexOf(".pdf") != -1) {
	//
	// } else {
	// Date date = marriage.getMarriageDate();
	// SimpleDateFormat sdfyyyy = new SimpleDateFormat("yyyy");
	// String year = sdfyyyy.format(date);// 创建年目录
	// String stts = marriage.getMarriageStatus();
	// String pathstatus = null;
	// if (stts.equals("结婚")) {
	// pathstatus = "marriage";
	// } else {
	// pathstatus = "divorce";
	// }
	// String filepath = session.getServletContext().getRealPath(
	// "photo/" + year + "/" + pathstatus + "/" + path + "/");
	// File f = new File(filepath);
	// if (!f.isDirectory()) {
	// f.mkdirs();
	// }
	//
	// // ===========================
	// logger.debug("filepath:{}", filepath);
	// logger.debug("size:{}", file.getSize());
	// logger.debug("type:{}", file.getContentType());
	//
	// try {
	// String orignalFilename = file.getOriginalFilename();
	// if (orignalFilename != null) {
	// String[] split = orignalFilename.split("\\.");
	// if (split != null && split.length > 0)
	// file.transferTo(new File(filepath + "/"
	// + System.currentTimeMillis() + "." + split[1]));
	// }
	// } catch (IllegalStateException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// } catch (IOException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// }
	// }
	//
	// //
	// =============================================================================
	// @RequestMapping(value = "/import", method = RequestMethod.GET)
	// public ModelAndView importExcelGet() {
	// logger.debug("import");
	// return new ModelAndView("manager/import");
	// }
	//
	// @RequestMapping(value = "/import", method = RequestMethod.POST)
	// public ModelAndView importExcel(HttpSession session,
	// @RequestParam MultipartFile file) {
	// String userId = session.getAttribute(Constants.USER_ID).toString();
	// String filepath = session.getServletContext().getRealPath(
	// "excel" + File.separator);
	// File f = new File(filepath);
	// if (!f.isDirectory()) {
	// f.mkdirs();
	// }
	// File excel = null;
	// String suffix = null;
	// logger.debug("filepath:{},size:{}", filepath, file.getSize());
	// try {
	// String orignalFilename = file.getOriginalFilename();
	// if (orignalFilename != null) {
	// String[] split = orignalFilename.split("\\.");
	// if (split != null && split.length > 1) {
	// suffix = split[1];
	// excel = new File(filepath + "/"
	// + System.currentTimeMillis() + "." + split[1]);
	// } else {
	// return new ModelAndView("manager/import");
	// }
	// file.transferTo(excel);
	// }
	// } catch (IllegalStateException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// } catch (IOException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// if (excel != null) {
	// if (suffix.equals("txt")) {// 解析txt
	// logger.debug("parse txt");
	// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	// try {
	// FileInputStream fis = new FileInputStream(excel);
	// InputStreamReader isr = new InputStreamReader(fis, "gbk");
	// BufferedReader reader = new BufferedReader(isr);
	// String line;
	// StringBuffer sb = new StringBuffer();
	// Marriage marriage = null;
	// List<Marriage> list = new ArrayList<>();
	// reader.readLine();
	// while ((line = reader.readLine()) != null) {
	// sb.append(line).append("\r\n");
	// String[] split = line.split("\t");
	// marriage = new Marriage();
	// String status = getMarriageStatus(split[2]);
	// if (status.equals("离婚")) {
	// marriage.setMarriageId(split[2]);
	// marriage.setMarriageDate(sdf.parse(split[1]));
	// marriage.setManId(split[4]);
	// marriage.setManName(split[6]);
	// marriage.setWomanId(split[15]);
	// marriage.setWomanName(split[17]);
	// marriage.setMarriageStatus(getMarriageStatus(split[2]));
	// marriage.setCreateUserId(userId);
	// marriage.setPhotoPath(split[1] + "_" + split[5]);
	// list.add(marriage);
	// } else if (status.equals("结婚")) {
	// marriage.setMarriageId(split[2]);
	// marriage.setMarriageDate(sdf.parse(split[1]));
	// marriage.setManId(split[5]);
	// marriage.setManName(split[7]);
	// marriage.setWomanId(split[17]);
	// marriage.setWomanName(split[19]);
	// marriage.setMarriageStatus(getMarriageStatus(split[2]));
	// marriage.setCreateUserId(userId);
	// marriage.setPhotoPath(split[1] + "_" + split[5]);
	// list.add(marriage);
	// } else {
	//
	// }
	// //System.out.println(line);
	// }
	//
	// for (Iterator<Marriage> iterator = list.iterator(); iterator
	// .hasNext();) {
	// Marriage record = (Marriage) iterator.next();
	// logger.info(record.toString());
	// marriageService.insert(record);
	// }
	// } catch (Exception e) {
	// logger.error("txt parse error!");
	// deleteDirectory(filepath);
	// return new ModelAndView("manager/import_error");
	// }
	//
	// } else {// 解析excel
	// parse(excel, 0, userId);
	// }
	// deleteDirectory(filepath);
	// } else {
	//
	// }
	// return new ModelAndView("manager/import_success");
	// }
	//
	// private String getMarriageStatus(String id) {
	// String status = null;
	// if (id != null) {
	// char c = id.charAt(0);
	// if (c == 'J') {
	// status = "结婚";
	// } else if (c == 'L') {
	// status = "离婚";
	// }
	// if(status!=null){
	// return status;
	// }
	// //哈阿结字011101105
	// if(id.indexOf("结")!=-1){
	// status = "结婚";
	// }else if(id.indexOf("离")!=-1){
	// status = "离婚";
	// }
	// }
	// return status;
	// }
	//
	// private HSSFWorkbook hWorkbook;// excel 2003之前的版本
	// private XSSFWorkbook xWorkbook;// excel 2007-2012
	//
	// private Object hasParser(File file) {
	// try {
	// // 获取工作薄workbook
	// hWorkbook = new HSSFWorkbook(new FileInputStream(file));
	// logger.debug("excel 97-2003");
	// return hWorkbook;
	// } catch (Exception e) {
	// try {
	// xWorkbook = new XSSFWorkbook(new FileInputStream(file));
	// logger.debug("excel 2007-2010");
	// return xWorkbook;
	// } catch (FileNotFoundException e1) {
	// // TODO Auto-generated catch block
	// e1.printStackTrace();
	// } catch (IOException e1) {
	// // TODO Auto-generated catch block
	// e1.printStackTrace();
	// }
	// }
	// return null;
	// }
	//
	// /**
	// * 解析成实体
	// *
	// * @param row
	// * @return
	// */
	// private Marriage parseRow(List<Object> row, String createUserId) {
	// Marriage marriage = new Marriage();
	// marriage.setCreateUserId(createUserId);
	// marriage.setPhotoPath("excel_" + System.currentTimeMillis());
	// for (int j = 0; j < row.size(); j++) {
	// Object obj = row.get(j);
	// String value = "";
	// if (obj != null) {
	// value = String.valueOf(obj).trim();
	// if (value.getBytes().length > 0) {
	// int c = (int) value.charAt(0);
	// if (c == 160) {
	// value = value.substring(1);
	// }
	// }
	// }
	// switch (j) {
	// case 0:
	// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	// try {
	// marriage.setMarriageDate(sdf.parse(value));
	// } catch (ParseException e) {
	// // logger.error("error:{}", e.getMessage());
	// }
	// break;
	// case 1:
	// // 提交时间
	// marriage.setMarriageId(value);
	// break;
	// case 2:
	// // 提交时间
	// marriage.setMarriageStatus(value);
	// break;
	// case 3:
	// // 收款账户
	// marriage.setManId(value);
	// break;
	// case 4:
	// // 收款名称
	// marriage.setManName(value);
	// break;
	// case 5:
	// // 金额
	// marriage.setWomanId(value);
	// break;
	// case 6:
	// // 状态
	// marriage.setWomanName(value);
	// break;
	// }
	//
	// }
	// logger.debug(marriage.toString());
	// marriageService.insertSelective(marriage);
	// return marriage;
	// }

	// /**
	// * 解析成集合
	// *
	// * @param file
	// * @return
	// */
	// public List<Marriage> parse(File file, int sheetNumber, String createUserId)
	// {
	// List<Marriage> list = null;
	// // 判断excel版本
	// Object obj = hasParser(file);
	// if (obj == null) {
	// return list;
	// }
	// list = new ArrayList<Marriage>();
	//
	// if (obj instanceof HSSFWorkbook) {// 97-2003
	// HExcelSheetParser parser = new HExcelSheetParser(file);
	// List<List<Object>> datas = parser.getDatasInSheet(sheetNumber);
	// for (int i = 1; i < datas.size(); i++) {
	// List<Object> row = datas.get(i);
	// list.add(parseRow(row, createUserId));
	// }
	// } else if (obj instanceof XSSFWorkbook) { // 2003-2010
	// XExcelSheetParser parser = new XExcelSheetParser(file);
	// List<List<Object>> datas = parser.getDatasInSheet(sheetNumber);
	// for (int i = 1; i < datas.size(); i++) {
	// List<Object> row = datas.get(i);
	// list.add(parseRow(row, createUserId));
	// }
	// }
	//
	// return list;
	// }

	/**
	 * 删除目录（文件夹）以及目录下的文件
	 * 
	 * @param sPath
	 *            被删除目录的文件路径
	 * @return 目录删除成功返回true，否则返回false
	 */
	public boolean deleteDirectory(String sPath) {
		// 如果sPath不以文件分隔符结尾，自动添加文件分隔符
		if (!sPath.endsWith(File.separator)) {
			sPath = sPath + File.separator;
		}
		File dirFile = new File(sPath);
		// 如果dir对应的文件不存在，或者不是一个目录，则退出
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			return false;
		}
		boolean flag = true;
		// 删除文件夹下的所有文件(包括子目录)
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 删除子文件
			if (files[i].isFile()) {
				flag = deleteFile(files[i].getAbsolutePath());
				if (!flag)
					break;
			} // 删除子目录
			else {
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag)
					break;
			}
		}
		if (!flag)
			return false;
		// 删除当前目录
		if (dirFile.delete()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 删除单个文件
	 * 
	 * @param sPath
	 *            被删除文件的文件名
	 * @return 单个文件删除成功返回true，否则返回false
	 */
	public boolean deleteFile(String sPath) {
		boolean flag = false;
		File file = new File(sPath);
		// 路径为文件且不为空则进行删除
		if (file.isFile() && file.exists()) {
			file.delete();
			flag = true;
		}
		return flag;
	}
}
